<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" size="small" :model="queryParams" class="demo-form-inline"
             v-hasPermi="['sa:bid:query']">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" clearable placeholder="请填写项目名称" />
      </el-form-item>
        <el-form-item label="项目编号" prop="projectNo">
          <el-input v-model="queryParams.projectNo" clearable placeholder="请填写政府采购项目编号" />
        </el-form-item>
      <el-form-item label="投标形式" prop="bidForm">
        <el-select v-model="queryParams.bidForm" clearable placeholder="请选择投标形式" style="width: 100%">
          <el-option v-for="item in dict.type.sys_task_bid_type" :key="item.value" :label="item.label" :value="+item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['sa:bid:add']"
                     @click="openDialog(null)">增加
          </el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table ref="tableRef" :data="tableData" v-loading="loading" highlight-current-row max-height="680"
              v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
      <el-table-column type="index" width="50" align="center" label="序号">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column property="projectName" label="项目名称" align="center"/>
      <el-table-column property="projectNo" label="项目编号" align="center"/>
      <el-table-column property="bidLink" label="公告链接" align="center"/>
      <el-table-column property="ceilingPrice" label="最高限价(元)" align="center"/>
      <el-table-column property="earnestMoney" label="保证金金额(元)" align="center"/>
      <el-table-column property="bidMoneyForm" label="保证金形式" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_deposit_form" :value="scope.row.bidMoneyForm"/>
        </template>
      </el-table-column>
      <el-table-column property="bidOpeningTime" label="开标时间" align="center"/>
      <el-table-column property="procurementUnit" label="采购单位" align="center"/>
      <el-table-column property="projectLeader" label="项目负责人" align="center"/>
      <el-table-column property="phone" label="联系方式" align="center"/>
      <el-table-column property="bidForm" label="投标形式" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_task_bid_type" :value="scope.row.bidForm"/>
        </template>
      </el-table-column>
      <el-table-column property="num" label="标书份数" align="center"/>
      <el-table-column property="hardwareManager" label="硬件负责人" align="center"/>
      <el-table-column property="softwareManager" label="软件负责人" align="center"/>
      <el-table-column property="schemeManager" label="方案负责人" align="center"/>
      <el-table-column property="finishTime" label="计划完成时间" align="center"/>
      <el-table-column property="mattersNeedAttention" label="特别事项" align="center"/>
      <el-table-column property="remark" label="备注" align="center"/>
      <el-table-column property="createBy" label="创建人" align="center" width="80"/>
      <el-table-column property="createTime" label="创建时间" align="center" sortable/>
      <el-table-column label="操作" align="center"
                       v-if="$auth.hasPermi('sa:bid:edit') || $auth.hasPermi('sa:bid:remove')">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['sa:bid:edit']"
                     @click="openDialog(scope.row)">修改
          </el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                         @confirm="deleteHandler(scope.row)">
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['sa:bid:remove']"
                       type="text" style="margin-left: 10px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="700px"
               :close-on-click-modal="false" :fullscreen="device === 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" class="demo-form"
               label-width="110px" :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目名称" prop="projectId">
              <el-input v-model="form.projectName" readonly placeholder="请选择项目" maxlength="50">
                <el-button slot="append" icon="el-icon-search" @click="handleShowProjectSelect"></el-button>
              </el-input>
              <ProjectSelect :showFlag.sync="showFlag" @onSelected="onItemSelected"/>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="form.projectNo" clearable placeholder="请填写政府采购项目编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="公告链接" prop="bidLink">
              <el-input v-model="form.bidLink" clearable placeholder="请填写招标公告链接" />
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="最高限价" prop="ceilingPrice">
              <el-input v-model="form.ceilingPrice" clearable placeholder="请填写最高限价">
                <span slot="append">元</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="保证金" prop="earnestMoney">
                <el-input v-model="form.earnestMoney" clearable placeholder="请填写保证金金额">
                  <template slot="append">元</template>
                </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="保证金形式" prop="bidMoneyForm">
              <el-select v-model="form.bidMoneyForm" clearable placeholder="请选择保证金形式" style="width: 100%">
                <el-option v-for="item in dict.type.sys_deposit_form" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="开标时间" prop="bidOpeningTime">
              <el-date-picker v-model="form.bidOpeningTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择开标时间"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="采购单位" prop="procurementUnit">
              <el-input v-model="form.procurementUnit" clearable placeholder="请填写采购单位全称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目负责人" prop="projectLeader">
              <el-input v-model="form.projectLeader" clearable placeholder="请填写项目负责人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" clearable placeholder="请填写联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="投标形式" prop="bidForm">
              <el-select v-model="form.bidForm" clearable placeholder="请选择投标形式" style="width: 100%">
                <el-option v-for="item in dict.type.sys_task_bid_type" :key="item.value" :label="item.label" :value="+item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="标书份数" prop="num">
              <el-input-number v-model="form.num" :min="0" clearable placeholder="请填写需要撰写标书的份数" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="硬件负责人" prop="hardwareManager">
              <el-input v-model="form.hardwareManager" clearable placeholder="请填写硬件负责人" :maxlength="100"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="软件负责人" prop="softwareManager">
              <el-input v-model="form.softwareManager" clearable placeholder="请填写软件负责人" :maxlength="100"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="方案负责人" prop="schemeManager">
              <el-input v-model="form.schemeManager" clearable placeholder="请填写方案撰写负责人" :maxlength="100"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="计划完成时间" prop="finishTime">
              <el-date-picker v-model="form.finishTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择计划完成时间"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="特别事项" prop="mattersNeedAttention">
              <el-input v-model="form.mattersNeedAttention" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" placeholder="请填写需要特别注意事项" :maxlength="250"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :maxlength="250" placeholder="请输入备注"
                        :autosize="{ minRows: 2 }"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/sa/task/bid";
import ProjectSelect from "@/components/ProjectSelect/index.vue";
import {getUserProfile} from "@/api/system/user";
import ProvinceData from '@/views/crm/data/province.json'
import {mapGetters} from 'vuex'

export default {
  name: 'TaskBidView',
  components: {ProjectSelect},
  dicts: ['sys_task_bid_type', 'sys_deposit_form'],
  data() {
    return {
      // 显示项目弹窗
      showFlag: false,
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        id: null,
        bidForm: "", // 投标形式（1.自销、2.代理）
        bidLink: "", // 招标公告链接
        bidMoneyForm: "", // 投标保证金形式
        bidOpeningTime: "", // 开标时间
        ceilingPrice: "", // 最高限价
        earnestMoney: "", // 投标保证金
        hardwareManager: "", // 硬件负责人（可选多个，用逗号分隔）
        mattersNeedAttention: "", // 需要特别注意事项
        num: "", // 需要撰写标书的份数
        phone: "", // 联系方式
        procurementUnit: "", // 采购单位全称
        projectId: null, // 项目ID
        projectLeader: "", // 项目负责人
        projectName: "", // 项目名称
        projectNo: "", // 政府采购项目编号
        schemeManager: "", // 方案负责人（可选多个，用逗号分隔）
        softwareManager: "", // 软件负责人（可选多个，用逗号分隔）
        finishTime: "", // 计划完成时间
        createBy: "", // 创建人
        createTime: "", // 创建时间
        remark: "", // 备注
        updateBy: "",
        updateTime: ""
      },
      // 表单的校验规则
      rules: {
        projectNo: [
          {required: true, message: "请填写项目编号", trigger: 'blur'}
        ],
        projectId: [
          {required: true, message: "请选择项目", trigger: 'change'}
        ],
        bidLink: [
          {required: true, message: "请填写招标公告链接", trigger: 'blur'}
        ],
        ceilingPrice: [
          {required: true, message: "请填写预算金额/最高限价", trigger: 'blur'}
        ],
        earnestMoney: [
          {required: true, message: "请填写保证金", trigger: 'blur'}
        ],
        bidMoneyForm: [
          {required: true, message: "请选择投标保证金形式", trigger: 'change'}
        ],
        bidOpeningTime: [
          {required: true, message: "请选择开标时间", trigger: 'change'}
        ],
        procurementUnit: [
          {required: true, message: "请填写采购单位", trigger: 'blur'}
        ],
        bidForm: [
          {required: true, message: "请选择投标形式", trigger: 'blur'}
        ],
        finishTime: [
          {required: true, message: "请选择计划完成时间", trigger: 'blur'}
        ]
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        projectName: "",
        projectNo: "",
        bidForm: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 项目数据
      projectList: [],
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    // this.getAllProjectList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 选中用户的回调
    onItemSelected(project) {
      this.form.projectId = project.id
      this.form.projectName = project.name
    },
    // 显示项目选择弹窗
    handleShowProjectSelect() {
      this.showFlag = true;
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {...row}
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = {...this.$options.data().form}
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.showFlag = false
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    // async exportHandler() {
    //   this.download('crm/newspaper/export', {
    //     ...this.queryParams,
    //     userId: this.user.userId,
    //     deptId: this.user.deptId,
    //   }, `newspaper_${new Date().getTime()}.xlsx`)
    // },
    // 表单提交
    submitForm(formName) {
      // if (this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        deptId: this.user.deptId,
        userId: this.user.userId,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.resetForm('queryFormRef')
    },
    // 取消按钮
    cancel() {
      this.showFlag = false
      this.dialogVisible = false;
    },
  },
}
</script>

<style scoped lang="scss">
.oneLine {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.cus_text {
  font-size: larger;
  margin: 10px;
}
</style>
